package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class SpecService {

    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;

    /**
     * 根据分类id查询规格组
     * @param id    分类id
     * @return
     */
    public List<SpecGroupDTO> querySpecGroupByCid(Long id) {
        //拼接条件
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(id);
        List<SpecGroup> list = specGroupMapper.select(specGroup);
        //判空
        if (CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        //返回
        return BeanHelper.copyWithCollection(list,SpecGroupDTO.class);
    }

    /**
     *
     * @param gid   规格组id
     * @param cid   分类id
     * @param searching     是否搜索
     * @return
     */
    public List<SpecParamDTO> querSpecParam(Long gid, Long cid, Boolean searching) {
        //判断:3个不能同时为空
        if (gid == null && cid == null && searching == null){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        SpecParam specParam = new SpecParam();
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setSearching(searching);

        List<SpecParam> list = specParamMapper.select(specParam);
        if (CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list,SpecParamDTO.class);
    }

    /**
     * 根据分类id查询规格组和组内的参数
     * @param id    分类id
     * @return
     */
    public List<SpecGroupDTO> querySpecByCategoryId(Long id) {
        //知识点: 避免在for循环查询sql语句, 很耗性能
        //1.获取规格组
        List<SpecGroupDTO> specGroupDTOList = querySpecGroupByCid(id);
        //2.根据分类id查询所有规格参数
        List<SpecParamDTO> specParamDTOS = querSpecParam(null, id, null);

        //3.对第2步的查询结果进行流的分组(根据groudId进行分组)
        Map<Long, List<SpecParamDTO>> listMap = specParamDTOS.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        //4.把规格参数放入组中
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            specGroupDTO.setParams(listMap.get(specGroupDTO.getId()));
        }
        return specGroupDTOList;
    }
}
